<template>
  <div class="myorder-container">
    <h2>我的订单</h2>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px ">
      <el-form-item label="订单编号">
        <el-input v-model="searchObj.order_no" placeholder="请输入订单编号" clearable />
      </el-form-item>
      <el-form-item label="订单状态" style="width: 200px;">
        <el-select v-model="searchObj.order_status" placeholder="全部状态" clearable>
          <el-option label="未确认" value="0"></el-option>
          <el-option label="已确认" value="1"></el-option>
          <el-option label="已取消" value="2"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 查询按钮 -->
    <el-form :inline="true" style="margin-bottom: 10px;">
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单表格 -->
    <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
    >
      <el-table-column label="订单编号" width="120">
        <template #default="scope">
          <el-tag>{{ scope.row.order_no }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单总金额" width="120">
        <template #default="scope">
          <el-tag type="primary">¥{{ scope.row.total_amount.toFixed(2) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="100">
        <template #default="scope">
          <el-tag
              :type="scope.row.order_status === 1 ? 'success' :
                   scope.row.order_status === 2 ? 'danger' : 'info'"
          >
            {{ scope.row.order_status === 1 ? '已确认' :
              scope.row.order_status === 2 ? '已取消' : '未确认' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" width="200">
        <template #default="scope">
          <el-tag>{{ scope.row.shipping_address }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收货人" width="100">
        <template #default="scope">
          <el-tag>{{ scope.row.receiver }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收货人电话" width="120">
        <template #default="scope">
          <el-tag>{{ scope.row.receiver_phone }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" width="160">
        <template #default="scope">
          <el-tag>{{ scope.row.create_time }}</el-tag>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              size="small"
              type="danger"
              @click="cancelOrder(scope.row)"
              :disabled="scope.row.order_status !== 0"
          >
            取消订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 10px;"
    />
  </div>
</template>

<script setup>
import orderAPI from '../api/order_api.js'
import { ref, onMounted, inject } from "vue";
import {ElMessageBox, ElMessage, ElOption, ElSelect, ElFormItem} from 'element-plus';

// 从全局获取登录用户信息
const loginAdmin = inject('loginAdmin');

// 表格数据 & 分页数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 查询条件（默认带上当前用户ID）
const searchObj = ref({
  current: 1,
  limit: 10,
  order_no: '',
  user_id: '', // 会在查询时被当前登录用户ID覆盖
  order_status: '',
});

// 页面加载时查询数据
onMounted(async () => {
  if (!loginAdmin.value.id) {
    ElMessageBox.alert('请先登录', '提示', { type: 'warning' });
    return;
  }
  await search();
});

// 通用查询方法（只查询当前用户的订单）
const search = async () => {
  if (!loginAdmin.value.id) return;

  loading.value = true;
  try {
    // 强制查询当前登录用户的订单
    const params = {
      ...searchObj.value,
      user_id: loginAdmin.value.id
    };
    const result = await orderAPI.page(params);
    tableData.value = result.data || [];
    total.value = result.count || 0;
  } catch (error) {
    console.error('获取订单数据失败:', error);
    ElMessage.error('获取订单数据失败');
  } finally {
    loading.value = false;
  }
};

// 分页改变（条数切换、页码切换）
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = () => {
  search();
};

// 点击查询按钮
const handlerSearch = async () => {
  searchObj.value.current = 1;
  await search();
};

// 取消订单（状态改为2）
const cancelOrder = async (row) => {
  if (row.order_status !== 0) {
    ElMessageBox.alert('只有未确认的订单可以取消', '提示', {
      confirmButtonText: '确定',
    });
    return;
  }

  ElMessageBox.confirm(
      '确认要取消该订单吗？',
      '取消提示',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await orderAPI.edit({
            id: row.id,
            order_status: 2 // 2表示已取消状态
          });
          ElMessage.success('订单已取消');
          await search();
        } catch (error) {
          console.error('取消订单失败:', error);
          ElMessage.error('取消订单失败');
        }
      })
      .catch(() => {});
};
</script>

<style scoped>
.myorder-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.el-table {
  margin-top: 10px;
}
</style>